package com.javasoft.service.LCB;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.javasoft.dao.XGX.QuestionDao;
import com.javasoft.entity.XGX.Question;
import com.javasoft.service.LCB.RemoveQueService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class RemoveQueServiceImpl extends ServiceImpl<QuestionDao, Question> implements RemoveQueService {

    @Autowired
    private QuestionDao questionDao;

    @Override
    public boolean addQuestionWithDuplicateCheck(Question question) {
        if (question == null || question.getDes() == null || question.getDes().trim().isEmpty()) {
            return false; // 如果问题为空或内容为空，返回false
        }

        // 使用HashSet进行去重检查
        Set<String> existingDescriptions = getExistingDescriptions();
        if (existingDescriptions.contains(question.getDes())) {
            return false; // 如果存在相同内容，返回false
        }

        try {
            question.setCreatTime(LocalDateTime.now()); // 设置创建时间为当前时间
            questionDao.insert(question); // 保存问题
            return true; // 成功保存，返回true
        } catch (Exception e) {
            log.error("添加错误: ", e);
            return false; // 发生异常，返回false
        }
    }

    /**
     * 获取所有问题的描述集合
     * @return 存储所有问题描述的HashSet
     */
    private Set<String> getExistingDescriptions() {
        LambdaQueryWrapper<Question> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(Question::getDes);
        List<Question> questions = list(wrapper);

        Set<String> descriptionsSet = new HashSet<>();
        for (Question question : questions) {
            descriptionsSet.add(question.getDes());
        }

        return descriptionsSet;
    }
}



